<?php
namespace Icsoc\DataBundle\Model;

use Doctrine\ORM\ORMException;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Icsoc\SecurityBundle\Entity\CcRoles;
use Icsoc\CoreBundle\Logger\ActionLogger;

/**
 * 下面中用到info参数的json格式大概为 ；filter搜素(具体提供搜素字段各个接口不一样)，
 *  pagination分页(rows 每页显示条数,page第几页)，sort排序
 *  {"pagination":{"rows":20,"page":"5"},"filter":{"endresult":"0"},"sort":{"field":"id","order":"desc"}}
 * Class BillModel
 * @package Icsoc\DataBundle\Model
 *
 */
class RoleModel extends BaseModel
{

    /** @var \Doctrine\ORM\EntityManager  */
    private $em;

    /** @var mixed 角色等级名称 */
    private $roleGradeName;

    /** @var array manage2的权限值 */
    private $crmRole = array(
        'gztlddj','gztkhgl','gztlxjlgl','xtglsjdr',
        'xtglsjdc','gztzsk','smsrecords','massmessage','modelpeizhi',
        'smsmodelmanage','sendsms','gztwjld','gztwdtx','xtglkhtp','xtglzdpz','xtgllbsz','know_power',
        'cle_power_update','cle_power_delete','record_update','record_delete','con_power_export',
    );

    /**
     * @var array
     * 角色等级 1=》主管，2=》组长，3=》员工
     */
    protected $role_grade = array(1,2,3);

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->em = $this->container->get('doctrine.orm.entity_manager');
        $this->roleGradeName = $this->container->getParameter('role_grade');
    }

    /**
     * 添加角色
     * @param array $params array('vcc_code'=>企业代码,'name'=>角色名称, 'role_grade'=>角色等级)
     * @return array
     */
    public function addRole(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $name = isset($params['name']) ? $this->purifyHtml($params['name']) : '';
        $roleGrade = isset($params['role_grade']) ? (int) $params['role_grade'] : '';
        $res = $this->validateRole(array('vcc_code'=>$vccCode, 'name'=>$name, 'role_grade'=>$roleGrade), 1);
        if ($res['code'] == '200') {
            $vid = $res['vid'];
        } else {
            return $res;
        }
        //入库
        $role = new CcRoles();
        $role->setVccId($vid);
        $role->setName($name);
        $role->setRoleGrade($roleGrade);
        $role->setActionList('');
        $role->setReportConfig('');
        $this->em->persist($role);
        $this->em->flush();
        $lastId = $role->getRoleId();

        //入日志
        $content = $this->container->get("translator")->trans("Add role %str%", array('%str%'=>$name));
        $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_ADD, $content);
        return array(
            'code' => 200,
            'message' => 'ok',
            'data'=>array(
                'role_id' => $lastId,
                'name' =>  $name,
                'role_grade' => isset($this->roleGradeName[$roleGrade]) ? $this->roleGradeName[$roleGrade] : '',
            )
        );
    }

    /**
     * 编辑角色
     * @param array $params array $params
     * array('vcc_code'=>企业代码,'name'=>角色名称, 'role_grade'=>角色等级. 'roleId'=>角色ID)
     * @return array|string
     */
    public function editRole(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $name = isset($params['name']) ? $this->purifyHtml($params['name']) : '';
        $roleGrade = isset($params['role_grade']) ? (int) $params['role_grade'] : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';
        $res = $this->validateRole(
            array('vcc_code'=>$vccCode, 'name'=>$name, 'role_grade'=>$roleGrade, 'role_id'=>$roleId),
            2
        );
        if ($res['code'] == '200') {
            $vid = $res['vid'];
        } else {
            return $res;
        }
        //验证角色是否属于 该企业
        $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vid, $roleId, 406);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        //入库
        $role = $this->em->getRepository("IcsocSecurityBundle:CcRoles")
            ->find($roleId);
        $oldName = $role->getName();
        $role->setName($name);
        $role->setRoleGrade($roleGrade);
        $this->em->flush();

        //入日志
        if ($oldName != $name) {
            $str = $oldName.'=>'.$name;
            $content = $this->container->get("translator")->trans("Update role %str%", array('%str%'=>$str));
            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);
        }

        //返回结果
        return array(
            'code' => 200,
            'message' => 'ok',
            'data'=>array(
                'role_id' => $roleId,
                'name' =>  $name,
                'role_grade' => isset($this->roleGradeName[$roleGrade]) ? $this->roleGradeName[$roleGrade] : '',
            )
        );
    }


    /**
     * 删除角色
     * @param array $params array('vcc_code'=>企业代码, 'role_id'=>角色ID)
     * @return array|string
     */
    public function delRole(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证角色是否属于 该企业
        $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vid, $roleId, 403);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        try {
            $where = "u.vccId = :vcc_id AND u.isDel = 0 AND u.userRole = :role";
            $params = array('vcc_id'=>$vid,'role'=>$roleId);
            $agents = $this->em->getRepository("IcsocSecurityBundle:WinAgent")->getByWhereFetchAgent($where, $params);
            if (empty($agents)) {
                $this->em->createQuery("DELETE IcsocSecurityBundle:CcRoles c WHERE c.roleId = :roleId")
                    ->setParameter('roleId', $roleId)->execute();
                $content = $this->container->get("translator")->trans("Delete role %str%", array('%str%'=>$roleId));
                $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);
                return array('code'=>'200', 'message'=>'ok');
            } else {
                $message = $this->container->get("translator")->trans('Failed to delete, the role has seat occupancy');
                return array('code'=>'405', 'message'=>$message);
            }
        } catch (ORMException $e) {
            //异常估计系统自己也会写日志了
            $message = $this->container->get("translator")->trans('Delete fail');
            return array('code'=>'404', 'message'=>$message);
        }
    }

    /**
     * 获取角色列表
     * @param array $params
     * array('vcc_code'=>企业代码, 'role_id'=>角色ID, 'flag'=>true,强制验证roleId, false可以不验证roleId flag可能在业务中需要)
     * @return array|string
     */
    public function getRoleList(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';
        $flag = isset($params['flag']) ? $params['flag'] : false;

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $where = array('vccId'=>$vid);
        if (!empty($roleId) || $flag) {
            //验证角色是否属于 该企业
            $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vid, $roleId, 403);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
            $where['roleId'] = $roleId;
        }
        try {
            /** @var \Icsoc\SecurityBundle\Entity\CcRoles $ccRole */
            $ccRoles = $this->em->getRepository("IcsocSecurityBundle:CcRoles")->findBy($where);
            if (empty($ccRoles)) {
                $message = $this->container->get("translator")->trans('The role does not exist');
                return array(
                    'code'=>404,
                    'message'=>$message,
                    'data'=>''
                );
            }
            $contents = array();
            foreach ($ccRoles as $ccRole) {
                $contents[] = array(
                    'name'=>$ccRole->getName(),
                    'role_id'=>$ccRole->getRoleId(),
                    'action_list'=>$ccRole->getActionList(),
                    'role_grade'=>$ccRole->getRoleGrade(),
                );
            }
            return array('code'=>200,'message'=>'ok','data'=>$contents);
        } catch (ORMException $e) {
            return array(
                'code'=>405,
                'message'=>$e->getMessage(),
                'data'=>''
            );
        }

    }

    /**
     * 设置角色权限值；
     * @param array $params array('vcc_code'=>企业代码, 'role_id'=>角色ID, 'action_list'=>权限值(gx,account,monitor))
     * @return array
     */
    public function setActionList(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';
        $actionList = isset($params['action_list']) ? $params['action_list'] : '';

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证角色是否属于 该企业
        $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vid, $roleId, 403);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        try {
            /** @var \Icsoc\SecurityBundle\Entity\CcRoles $ccRole */
            $ccRole = $this->em->getRepository("IcsocSecurityBundle:CcRoles")->find($roleId);
//            if (empty($ccRole)) {
//                $message = $this->container->get("translator")->trans('The role does not exist');
//                return array('ccode'=>404,'message'=>$message,'data'=>'');
//            }
            $oldList = $ccRole->getActionList();
            $crmStr = '';
            //保留以前的crm权限;
            foreach ($this->crmRole as $val) {
                if (strpos($oldList, $val) !== false) {
                    $crmStr.=$val.",";
                }
            }
            if ($oldList != $actionList) {
                //记录日志
                $str = $oldList.'=>'.$actionList;
                $content = $this->container->get("translator")->trans("Set action list %str%", array('%str%'=>$str));
                $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);
            }
            $actionList.=$crmStr;
            $ccRole->setActionList($actionList);
            $this->em->flush();
            return array('code'=>200, 'message'=>'ok');
        } catch (Exception $e) {
            return array('code'=>405,'message'=>$e->getMessage(),'content'=>'');
        }
    }

    /**
     * 设置角色报表配置；
     * @param array $params array('vcc_code'=>企业代码, 'role_id'=>角色ID, 'action_list'=>权限值(gx,account,monitor))
     * @return array
     */
    public function setReportConfig(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';
        $reportConfig = isset($params['report_config']) ? $params['report_config'] : '';
        $globalConfig = isset($params['global_config']) ? $params['global_config'] : '';
        $updateConfigs = isset($params['update_configs']) ? $params['update_configs'] : '';

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证角色是否属于 该企业
        $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vid, $roleId, 403);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $conn->beginTransaction();
        try {
            $conn->update('cc_roles', array('report_config' => $reportConfig), array('role_id'=>$roleId));

            /** 除了修改本身的角色配置，还要修改该企业下的其他角色的配置，因为可能有全局配置*/
            foreach ($updateConfigs as $otherRoleId => $otherRoleConfig) {
                if (!empty($otherRoleConfig)) {
                    $conn->update('cc_roles', array('report_config' => json_encode($otherRoleConfig)), array('role_id' => $otherRoleId));
                }
            }

            /**同时修改全局报表数据*/
            $globalInfo = $conn->fetchColumn("select id from cc_global_report_config where vcc_id = :vcc_id",array('vcc_id' => $vid));
            if (!empty($globalInfo)) {
                $conn->update('cc_global_report_config', array('report_config' => $globalConfig), array('vcc_id' => $vid));
            } else {
                $conn->insert('cc_global_report_config', array('vcc_id' => $vid,'report_config' => $globalConfig));
            }

            $conn->commit();
            $conn->close();

            return array('code'=>200, 'message'=>'ok');
        } catch (\Exception $e) {
            $conn->rollBack();
            $conn->close();
            return array('code'=>405, 'message'=>$e->getMessage(), 'content'=>'');
        }
    }

    /**
     * 设置角色监控配置；
     *
     * @param array $params array('vcc_code'=>企业代码, 'role_id'=>角色ID, 'monitor_info'=>监控配置信息)
     * @return array|string
     */
    public function setMonitorConfig(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';
        $monitorConfig = isset($params['monitor_info']) ? $params['monitor_info'] : '';

        /** 验证企业代码 */
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        /** 验证角色是否属于该企业 */
        $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vid, $roleId, 403);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        $monitorConfigs = json_decode($monitorConfig, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return array(
                'code'=>403,
                'message'=>json_last_error(),
            );
        }

        $conn = $this->container->get('doctrine.dbal.default_connection');
        $conn->beginTransaction();

        try {
            $ids = array();
            foreach ($monitorConfigs as $monitorConfig) {
                if (empty($monitorConfig['id'])) {
                    unset($monitorConfig['id']);
                    $conn->insert(
                        'cc_monitor_screen',
                        array(
                            'vcc_id' => $vid,
                            'role_id' => $roleId,
                            'screen_name' => $monitorConfig['name'],
                            'screen_info' => json_encode($monitorConfig),
                            'refresh_time' => $monitorConfig['refresh'],
                            'create_time' => time(),
                        )
                    );

                    $ids[] = $conn->lastInsertId();
                } else {
                    $ids[] = $monitorConfig['id'];
                    $id = $monitorConfig['id'];
                    unset($monitorConfig['id']);
                    if (count($monitorConfigs) == 1) {
                        $show = $isMainShow = 0;
                        if (!empty($monitorConfig) && is_array($monitorConfig)) {
                            $show = empty($monitorConfig['agent']['is_show']) ? 0 : $monitorConfig['agent']['is_show'];
                            if (!empty($monitorConfig['mainFields']) && is_array($monitorConfig['mainFields'])) {
                                foreach ($monitorConfig['mainFields'] as $key => $val) {
                                    if (!empty($val['fields'])) {
                                        $isMainShow = 1;
                                        break;
                                    }
                                }
                            }
                        }

                        if (empty($show) && empty($isMainShow)) {
                            $conn->delete(
                                'cc_monitor_screen',
                                array(
                                    'id' => $id,
                                )
                            );
                            break;
                        }
                    }

                    $conn->update(
                        'cc_monitor_screen',
                        array(
                        'vcc_id' => $vid,
                        'role_id' => $roleId,
                        'screen_name' => $monitorConfig['name'],
                        'screen_info' => json_encode($monitorConfig),
                        'refresh_time' => $monitorConfig['refresh'],
                        'create_time' => time(),
                        ),
                        array('id'=>$id)
                    );
                }
            }

            if (!empty($ids)) {
                $conn->query(
                    "DELETE FROM cc_monitor_screen WHERE role_id = '$roleId' AND id not in (".implode(',', $ids).")"
                );
            }

            $conn->commit();

            return array('code'=>200, 'message'=>'ok', 'data'=>$ids);
        } catch (\Exception $e) {
            $conn->rollBack();

            return array(
                'code'=>500,
                'message'=>$e->getMessage(),
            );
        }
    }

    /**
     * 公共验证方法
     * @param array $params
     * @param int $flag (1，为add, 2为update)
     * @return array|string
     */
    protected function validateRole(array $params, $flag = 1)
    {

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($params['vcc_code']);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证name
        $msg = $this->container->get('icsoc_data.validator')->isEmptyName($params['name'], 403, '角色名称为空或非法');
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证角色名称是否重复
        $where = " vcc_id = :vcc_id AND name = :name ";
        $par_arr = array('vcc_id' => $vid, 'name' => $params['name']);
        if ($flag == 2) {
            $where.=" AND role_id <> :role_id ";
            $par_arr['role_id'] = $params['role_id'];
        }
        $msg = $this->container->get('icsoc_data.validator')->existRole($where, $par_arr, '404');
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        //验证角色等级
        if (!in_array($params['role_grade'], $this->role_grade)) {
            $ret = array('code' => 405, 'message' => '角色等级有误');
            return $ret;
        }
        return array('code'=>200,'vid'=>$vid);
    }

    /**
     * @return string
     */
    public function randColor()
    {
        $str='0123456789ABCDEF';
        $estr='#';
        $len=strlen($str);
        for ($i=1; $i <= 6; $i++) {
            $num=rand(0, $len-1);
            $estr=$estr.$str[$num];
        }

        return strtolower($estr);
    }

    /**
     * @param int $roleId
     * @return array
     */
    public function getDataAuthority($roleId = 0)
    {
        if (empty($roleId)) {
            return array('code'=>401, 'message'=>'角色ID不能为空');
        }
        try {
            $conn = $this->container->get('doctrine.dbal.default_connection');
            $rst = $conn->fetchAssoc("SELECT user_type,user_queues FROM cc_roles WHERE role_id=$roleId");
        } catch (\Exception $e) {
            $this->container->get('logger')->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }

        return array('code'=>200, 'message'=>'success', 'data'=>$rst);
    }

    /**
     * @param array $params
     * @return array
     */
    public function setDataAuthority($params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $params['vcc_code'] : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';
        $dataInfo = isset($params['data_info']) ? $params['data_info'] : '';

        /** 验证企业代码 */
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (empty($roleId)) {
            return array('code'=>403, 'message'=>'角色ID不能为空');
        }

        /** 验证角色是否属于该企业 */
        $msg = $this->container->get('icsoc_data.validator')->checkRoleIfBelongsToVcc($vccId, $roleId, 404);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        $dataInfo = json_decode($dataInfo, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return array(
                'code'=>405,
                'message'=>json_last_error(),
            );
        }
        $data['user_type'] = isset($dataInfo['user_type']) ? $dataInfo['user_type'] : 0;
        $userQueues = isset($dataInfo['user_queues']) ? $dataInfo['user_queues'] : array();
        $userGroups = isset($dataInfo['user_groups']) ? $dataInfo['user_groups'] : array();

        switch ($data['user_type']) {
            case '0':
            case '2':
                $data['user_queues'] = '';
                break;
            case '1':
                $data['user_queues'] = implode(',', $userQueues);
                break;
            case '3':
                $data['user_queues'] = implode(',', $userGroups);
                break;
            default:
                $data['user_queues'] = '';
        }
        try {
            $conn = $this->container->get('doctrine.dbal.default_connection');
            $conn->update('cc_roles', $data, array('role_id'=>$roleId));

            $this->setAgentRoleInfo(array('vcc_code'=>$vccCode, 'role_id'=>$roleId));

        } catch (\Exception $e) {
            $this->container->get('logger')->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }

        return array('code'=>200, 'message'=>'success');
    }

    /**
     * 获取角色信息
     *
     * @param array $params
     * @return array|string
     */
    public function getRoleInfo($params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $params['vcc_code'] : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';

        /** 验证企业代码 */
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($roleId)) {
            return array('code'=>403, 'message'=>'角色ID不能为空');
        }

        try {
            $conn = $this->container->get('doctrine.dbal.default_connection');
            $rolrInfo = $conn->fetchAssoc(
                "SELECT user_type,user_queues FROM cc_roles WHERE role_id = :role_id",
                array('role_id' => $roleId)
            );

            return array('code'=>200, 'message'=>'success', 'data'=>$rolrInfo);
        } catch (\Exception $e) {
            $this->container->get('logger')->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }
    }

    /**
     * 设置坐席数据权限
     *
     * @param array $params
     * @return array|string
     */
    public function setAgentRoleInfo($params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $params['vcc_code'] : '';
        $roleId = isset($params['role_id']) ? (int) $params['role_id'] : '';

        /** 验证企业代码 */
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($roleId)) {
            return array('code'=>403, 'message'=>'角色ID不能为空');
        }

        try {
            $conn = $this->container->get('doctrine.dbal.default_connection');
            $rolrInfo = $conn->fetchAssoc(
                "SELECT user_type,user_queues FROM cc_roles WHERE role_id = :role_id",
                array('role_id' => $roleId)
            );

            $conn->update(
                "win_agent",
                array('user_type'=>$rolrInfo['user_type'], 'user_queues'=>$rolrInfo['user_queues']),
                array('user_role'=>$roleId)
            );

            return array('code'=>200, 'message'=>'success');
        } catch (\Exception $e) {
            $this->container->get('logger')->error($e->getMessage());

            return array('code'=>400, 'message'=>'数据库执行错误');
        }
    }

    /**
     * 获取用户自定的报表配置信息
     *
     * @param string $reportType
     * @param int    $roleId
     * @return array
     */
    public function getReportConfig($reportType = '', $roleId = 0)
    {
        $conn = $this->container->get('doctrine.dbal.default_connection');

        if (!empty($roleId)) {
            $result = $conn->fetchColumn(
                "SELECT report_config FROM cc_roles WHERE role_id = :role_id",
                array('role_id' => $roleId,
                )
            );
        }

        $user = $this->container->get("security.token_storage")->getToken()->getUser();
        $loginType = $user->getLoginType();
        $reportConfigs = array();
        if ($loginType == 2) {
            $userRole = $user->getUserRole();
            $result = $conn->fetchColumn(
                "SELECT report_config FROM cc_roles WHERE role_id = :role_id",
                array('role_id' => $userRole,
                )
            );
        }

        if (!empty($result)) {
            $configs = json_decode($result, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                $this->container->get('logger')->error(json_last_error());

                return array(
                    'code'=>403,
                    'message'=>json_last_error(),
                );
            }

            if (empty($reportType)) {
                $reportConfigs = $configs;
            }

            if (isset($configs[$reportType])) {
                $reportConfigs = $configs[$reportType];
            }
        }

        return array('code'=>200, 'message'=>'success', 'data' => $reportConfigs);
    }

    /**
     * 获取配置的计算项
     *
     * @param int $roleId
     * @return array
     */
    public function getcalculateItem($roleId = 0)
    {
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $calculateItems = array();

        if (!empty($roleId)) {
            //获取角色的配置项
            $config = $conn->fetchAll(
                "SELECT report_config FROM cc_roles WHERE role_id = $roleId"
            );

            //判断配置项中是否有需要计算的项
            $configs = array();
            $calculateItems = array();
            foreach ($config as $val) {
                foreach ($val as $v) {
                    $configs[] = json_decode($v, true);
                    foreach ($configs as $configsVal) {
                        if (!empty($configsVal)) {
                            foreach ($configsVal as $key => $val) {
                                $calculateItems[$key] = $val['calculateItems'];
                            }
                        }
                    }
                }
            }
        } else {
            $loginType = $this->container->get("security.token_storage")->getToken()->getUser()->getLoginType();
            if ($loginType == 2) {
                $userRole = $this->container->get("security.token_storage")->getToken()->getUser()->getUserRole();

                //获取角色的配置项
                $config = $conn->fetchAll(
                    "SELECT report_config FROM cc_roles WHERE role_id = $userRole"
                );

                //判断配置项中是否有需要计算的项
                $configs = array();
                $calculateItems = array();
                foreach ($config as $val) {
                    foreach ($val as $v) {
                        $configs[] = json_decode($v, true);
                        foreach ($configs as $configsVal) {
                            if (!empty($configsVal)) {
                                foreach ($configsVal as $key => $val) {
                                    $calculateItems[$key] = $val['calculateItems'];
                                }
                            }
                        }
                    }
                }
            }
        }

        
        return $calculateItems;
    }

    /**
     * 通过企业代码获取所有已绑定的中继号码
     * @param int $vccId
     * @return array
     */
    public function getPhonesByVccId($vccId)
    {
        $phones = array();
        if (empty($vccId)) {
            return $phones;
        }
        try {
            $conn = $this->container->get('doctrine.dbal.default_connection');
            $phoneInfo = $conn->fetchAll(
                "SELECT phone 
                FROM cc_phone400s 
                WHERE if_bind = :if_bind AND vcc_id = :vcc_id",
                array(
                    "if_bind" => 1,
                    "vcc_id" => $vccId,
                    )
            );
            if (is_array($phoneInfo) && !empty($phoneInfo)) {
                foreach ($phoneInfo as $phone) {
                    if (!empty($phone['phone'])) {
                        $phones[] = $phone['phone'];
                    }
                }
            }
            $phones = array_unique($phones);
        } catch (\Exception $e) {
            $this->container->get('logger')->error(sprintf("search phones info is exception, Exception info is %s.", $e->getMessage()));
        }

        return $phones;
    }

    /**
     * 获取该企业的业务组数据
     * @param int $vccId
     * @return array
     */
    public function getGroupDataByVccId($vccId)
    {
        $groups = array();
        if (empty($vccId)) {
            return $groups;
        }
        try {
            $conn = $this->container->get('doctrine.dbal.default_connection');
            $groupInfo = $conn->fetchAll(
                "SELECT group_id,group_name 
                FROM win_group WHERE vcc_id = :vcc_id AND is_del=0 ",
                array(
                    "vcc_id" => $vccId,
                )
            );
            if (is_array($groupInfo) && !empty($groupInfo)) {
                foreach ($groupInfo as $group) {
                    $groups[$group['group_id']] = empty($group['group_name']) ? "未定义" : $group['group_name'];
                }
            }
        } catch (\Exception $e) {
            $this->container->get('logger')->error(sprintf("search group info is exception, Exception info is %s.", $e->getMessage()));
        }

        return $groups;
    }

    /**
     * 给报表配置项按升序排序
     * @param array $reportItems
     * @param int $defaultSort 默认排序值
     * @return array
     */
    public function getReportConfigOrder($reportItems, $defaultSort = 100)
    {
        $arr = array();
        foreach ($reportItems as $item => $config) {
            if (isset($config['sort'])) {
                $arr[$item] = $config['sort'];
            } else {
                $arr[$item] = $defaultSort;
            }
        }
        if (!empty($arr)) {
            asort($arr);
            $res = array();
            foreach ($arr as $item => $sort) {
                $res[$item] = $reportItems[$item];
            }
            return $res;
        }

        return $reportItems;
    }

    public function setCopyRole($param)
    {
        $copyId = $param['roleId'];
        $name = $param['name'];
        $vccId = $param['vccId'];

        //先查出要复制的角色的信息，然后再重新插入一份到cc_roles表中
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $roleId = '';
        $roleGrade = '';
        try {
            //查询角色配置数据
            $roleInfo = $conn->fetchAssoc(
                'select * from cc_roles where vcc_id = :vcc_id and role_id = :role_id',
                array(
                    'vcc_id' => $vccId,
                    'role_id' => $copyId
                )
            );
            //查询监控配置数据
            $monitorInfo = $conn->fetchAll(
                "select * from cc_monitor_screen where vcc_id = :vcc_id and role_id = :role_id",
                array(
                    'vcc_id' => $vccId,
                    'role_id' => $copyId
                )
            );
            $conn->beginTransaction();
            if (!empty($roleInfo)) {
                $res = $this->validateRole(array('vcc_code' => $param['vccCode'], 'name' => $name, 'role_grade' => $roleInfo['role_grade']), 1);
                if ($res['code'] == 200) {
                    $vccId = $res['vid'];
                } else {
                    return $res;
                }
                $conn->insert(
                    'cc_roles',
                    array(
                        'vcc_id' => $vccId,
                        'name' => $name,
                        'role_grade' => $roleInfo['role_grade'],
                        'action_list' => $roleInfo['action_list'],
                        'group_id' => $roleInfo['group_id'],
                        'report_config' => $roleInfo['report_config'],
                        'user_type' => $roleInfo['user_type'],
                        'user_queues' => $roleInfo['user_queues'],
                    )
                );
                $roleId = $conn->lastInsertId();
                $roleGrade = $roleInfo['role_grade'];
            }

            foreach ($monitorInfo as $monitor) {
                if (!empty($monitor)) {
                    $conn->insert(
                        'cc_monitor_screen',
                        array(
                            'vcc_id' => $vccId,
                            'screen_name' => $monitor['screen_name'],
                            'screen_info' => $monitor['screen_info'],
                            'role_id' => $roleId,
                            'create_time' => time(),
                            'refresh_time' => $monitor['refresh_time']
                        )
                    );
                }
            }
            $conn->commit();
        } catch(\Exception $e) {
            $this->container->get('logger')->error(sprintf("copy role exception, Exception info is %s.", $e->getMessage()));
            $conn->rollBack();
        }

        return array(
            'code' => 200,
            'message' => 'ok',
            'data' => array(
                'role_id' => $roleId,
                'name' => $name,
                'role_grade' => isset($this->roleGradeName[$roleGrade]) ? $this->roleGradeName[$roleGrade] : ''
            )
        );
    }
}
